package examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.*;

/**
 * @author Jay
 */
public class CountDownLatchExample2 {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(), new ThreadFactory() {
            int id = 0;

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "file-read-thread-" + id++);
            }
        });

        long start = System.currentTimeMillis();
        executor.submit(new FileReadTask("D:/test1.txt", countDownLatch));
        executor.submit(new FileReadTask("D:/test2.txt", countDownLatch));
        executor.submit(new FileReadTask("D:/test3.txt", countDownLatch));


        try {
            countDownLatch.await();
            executor.shutdown();
            long end = System.currentTimeMillis();
            System.out.println(end - start);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class FileReadTask implements Runnable {

        private final String filePath;
        private final StringBuilder builder;
        private final CountDownLatch countDownLatch;
        public FileReadTask(String path, CountDownLatch countDownLatch){
            this.filePath = path;
            this.builder = new StringBuilder();
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            File file = new File(this.filePath);
            FileInputStream inputStream;
            try {
                inputStream = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int bufferLen = 1024;
                while(inputStream.read(buffer, 0, bufferLen) != -1) {
                    builder.append(Arrays.toString(buffer));
                }
                inputStream.close();
                System.out.println(Thread.currentThread().getName() + "done");

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }

        }
    }
}
